package cc.rengu.igas.bomp.core.service.trans;

import cc.rengu.igas.bomp.common.constant.BompAppParamConstant;
import cc.rengu.igas.bomp.common.constant.DubboMethodConstant;
import cc.rengu.igas.bomp.common.dao.AlipayMchntInfoMapper;
import cc.rengu.igas.bomp.common.dao.MchntAcctInfoMapper;
import cc.rengu.igas.bomp.common.dao.MchntBaseInfoMapper;
import cc.rengu.igas.bomp.common.dao.impl.AlipayMchntInfoMapperImpl;
import cc.rengu.igas.bomp.common.dao.impl.MchntAcctInfoMapperImpl;
import cc.rengu.igas.bomp.common.dao.impl.MchntBaseInfoMapperImpl;
import cc.rengu.igas.bomp.common.entity.AlipayMchntInfo;
import cc.rengu.igas.bomp.common.entity.MchntAcctInfo;
import cc.rengu.igas.bomp.common.entity.MchntBaseInfo;
import cc.rengu.igas.bomp.common.enums.RespCodeEnum;
import cc.rengu.igas.bomp.core.service.base.ManageService;
import cc.rengu.igas.bomp.facade.request.AlipayActivityApplyRequest;
import cc.rengu.igas.bomp.facade.response.AlipayActivityApplyResponse;
import cc.rengu.igas.channel.alipay.facade.bean.BankCardInfo;
import cc.rengu.igas.channel.alipay.facade.request.ActivityCreateRequest;
import cc.rengu.igas.channel.alipay.facade.response.ActivityCreateResponse;
import cc.rengu.igas.channel.alipay.facade.result.Result;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.entity.ChannelCallCfg;
import cc.rengu.oltp.service.common.enums.OltpRpcdEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.DateUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by zhangxuran on 2020/03/24 特殊费率商户申请服务
 */
public class AlipayActivityApplyService extends ManageService {

    @Override
    protected Object bizBeforeCust() throws Exception {
        AlipayActivityApplyRequest alipayActivityApplyRequest = new AlipayActivityApplyRequest();
        ConvertUtil.convertOutput(alipayActivityApplyRequest);
        return alipayActivityApplyRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        AlipayActivityApplyRequest alipayActivityApplyRequest = (AlipayActivityApplyRequest) request;
        AlipayActivityApplyResponse alipayActivityApplyResponse = new AlipayActivityApplyResponse();
        /*获取法人行号信息*/
        String instId = alipayActivityApplyRequest.getHeader().getInstId();
        /* 获取商户号 */
        String mchntNo = alipayActivityApplyRequest.getMchntNo();
        /* 获取用户标识 */
        String userId = alipayActivityApplyRequest.getUserId();
        /*请求参数必填性校验*/
        if (StringUtil.isEmptyOrNull(instId) || StringUtil.isEmptyOrNull(mchntNo) || StringUtil.isEmptyOrNull(userId)) {
            rglog.error("必填性校验错误!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }
        /*根据商户查询商户基本信息*/
        MchntBaseInfoMapper mchntBaseInfoMapper = new MchntBaseInfoMapperImpl();
        MchntBaseInfo mchntBaseInfo = mchntBaseInfoMapper.selectMchntBaseInfoByPrimaryKey(instId, mchntNo);
        if (null == mchntBaseInfo) {
            rglog.error("商户基本信息查询失败!");
            throw new BizException(RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespCode(), RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespDesc());
        }
        /* 根据商户号查询支付宝商户信息 */
        AlipayMchntInfoMapper alipayMchntInfoMapper = new AlipayMchntInfoMapperImpl();
        AlipayMchntInfo alipayMchntInfo = alipayMchntInfoMapper.selectAlipayMchntInfoByPrimaryKey(instId, mchntNo);
        if (null == alipayMchntInfo || !"0".equals(alipayMchntInfo.getSpecialRateApplyFlag())) {
            rglog.error("支付宝商户信息为空!");
            throw new BizException(RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespCode(), RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespDesc());
        }
        /* 获取通道标识 */
        List<ChannelCallCfg> channelCallCfgList = txnInfo.getChannelCallCfgList();
        List<ChannelCallCfg> msgDstchannelCallCfgList = channelCallCfgList.stream().filter(item -> item.getCallChannelId().equals("ALIP")).collect(Collectors.toList());
        ChannelCallCfg channelCallCfg = msgDstchannelCallCfgList.get(0);
        String channelId = channelCallCfg.getCallChannelId();
        /* 获取通道类型 */

        String channelType = alipayMchntInfo.getDstChannelType();
        /* 通过dubbo服务调用通道方法查询支付宝商户信息 */
        DubboService dubboService = new DubboServiceImpl();
        /* 请求信息处理 */
        ActivityCreateRequest activityCreateRequest = new ActivityCreateRequest();
        /*设置报文头*/
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String sysSeqNum = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM);
        cc.rengu.igas.channel.alipay.facade.base.Header header = new cc.rengu.igas.channel.alipay.facade.base.Header();
        header.setInstId(instId);
        header.setTxnNum(channelCallCfg.getCallChannelTxn());
        header.setTraceNo(sysSeqNum + channelCallCfg.getCallIndex());
        header.setSrcSysId(AppParamConstant.SYS_ID);
        header.setChanlId(BompAppParamConstant.BOMP_SYS_ID);
        header.setBizType(channelCallCfg.getBizType());
        header.setTransTime(DateUtil.getCurrentTime());
        header.setTransDate(DateUtil.getCurrentDate());
        activityCreateRequest.setHeader(header);
        /*通道标识赋值*/
        activityCreateRequest.setChannelId(channelId);
        /*通道类型赋值*/
        activityCreateRequest.setChannelType(channelType);
        /*支付宝商户号赋值*/
        activityCreateRequest.setAliMchntNo(alipayMchntInfo.getAlipayMchntNo());
        /* 活动类型赋值*/
        activityCreateRequest.setActivityType("INDUSTRY_SPECIAL");
        /*商户名称赋值*/
        activityCreateRequest.setMchntName(mchntBaseInfo.getMchntName());
        /*商户简称赋值*/
        activityCreateRequest.setMchntAbbr(mchntBaseInfo.getMchntSimpleName());
        /*收银台照片赋值*/
        activityCreateRequest.setCheckstandPic(alipayActivityApplyRequest.getCheckstandImage());
        /*门头照赋值*/
        activityCreateRequest.setShopEntrancePic(alipayActivityApplyRequest.getShopEntranceImage());
        /*营业执照赋值*/
        activityCreateRequest.setLicensePic(alipayActivityApplyRequest.getBusinessLicenseImage());
        /*店内环境照赋值*/
        activityCreateRequest.setIndoorPic(alipayActivityApplyRequest.getIndoorImage());
        /*主流餐饮平台入驻证明赋值*/
        activityCreateRequest.setSettledPic(alipayActivityApplyRequest.getSettledImage());
        /*事业单位法人证书图片赋值*/
        activityCreateRequest.setInstitutionalOrgPic(alipayActivityApplyRequest.getInstitutionalOrganizationImage());
        /*法人身份证正面图片赋值*/
        activityCreateRequest.setLegalPersonFrontPic(alipayActivityApplyRequest.getCertFaceImage());
        /*法人身份证反面图片赋值*/
        activityCreateRequest.setLegalPersonBackPic(alipayActivityApplyRequest.getCertBackImage());
        /*办学资质图片赋值*/
        activityCreateRequest.setSchoolLicensePic(alipayActivityApplyRequest.getRunSchoolLicenseImage());
        /*组织机构代码证图片赋值*/
        activityCreateRequest.setOrgCertPic(alipayActivityApplyRequest.getOrgCertImage());
        /*法人登记证书图片赋值*/
        activityCreateRequest.setLegalPersonRegistrationPic(alipayActivityApplyRequest.getArtifRegistrationImage());
        /*医疗执业许可证图片赋值*/
        activityCreateRequest.setMedicalInstrumentPracticPic(alipayActivityApplyRequest.getMedicalInstrumentPracticeLicenseImage());
        /*收费样本赋值*/
        activityCreateRequest.setChargeSamplePic(alipayActivityApplyRequest.getChargeSampleImage());
        /*民办非企业单位登记证书图片赋值*/
        activityCreateRequest.setPriNonenterpriseUnitsPic(alipayActivityApplyRequest.getPrivateNonenterpriseUnitsImage());
        /*照会赋值*/
        activityCreateRequest.setDiplomaticNotePic(alipayActivityApplyRequest.getDiplomaticNoteImage());
        /*证明文件图片赋值*/
        activityCreateRequest.setCertificateFilePic(alipayActivityApplyRequest.getCertificateFileImage());

        /*查询商户结算账户信息*/
        MchntAcctInfoMapper mchntAcctInfoMapper = new MchntAcctInfoMapperImpl();
        MchntAcctInfo mchntAcctInfo = mchntAcctInfoMapper.selectMchntAcctInfoByPrimaryKey(instId, mchntNo, "*", "00");
        BizResponse<AlipayActivityApplyResponse> bizResponse = new BizResponse<>();
        if (null != mchntAcctInfo) {
            BankCardInfo bankCardInfo = new BankCardInfo();
            /*结算账户赋值*/
            bankCardInfo.setAcctNo(mchntAcctInfo.getSettleAcctNo());
            /*结算账户名赋值*/
            bankCardInfo.setAcctName(mchntAcctInfo.getSettleAcctName());
            /*开户行名赋值*/
            bankCardInfo.setBankName(mchntAcctInfo.getAcctOpenBankName());
            /*结算账户信息赋值*/
            activityCreateRequest.setBankCardInfo(bankCardInfo);
        } else {
            rglog.error("商户结算账户信息为空!");
            throw new BizException(RespCodeEnum.QUERY_ACCT_INFO_ERROR.getRespCode(), RespCodeEnum.QUERY_ACCT_INFO_ERROR.getRespDesc());
        }
        /* 调用dobbu服务并接收响应信息 */
        Result<ActivityCreateResponse> result = (Result<ActivityCreateResponse>) dubboService.callDubboService(DubboMethodConstant.DUBBO_ALIPAY_MCHNT_SERVICE, "activityCreate", activityCreateRequest);
        if (null == result || !result.isSuccess()) {
            rglog.error("调dobbu失败，respCode={},respDesc={}", OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR.getRespCode(), OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc());
            bizResponse.setResult(alipayActivityApplyResponse);
            bizResponse.setRspSysId(AppParamConstant.SYS_ID);
            bizResponse.setRespCode(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR.getRespCode());
            bizResponse.setRespDesc(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc());
            return bizResponse;
        } else if (!OltpRpcdEnum.TRANS_SUCCESS.getRespCode().equals(result.getResult().getRespCode())) {
            alipayActivityApplyResponse.setRespCode(result.getResult().getRespCode());
            alipayActivityApplyResponse.setRespDesc(result.getResult().getRespDesc());
            bizResponse.setResult(alipayActivityApplyResponse);
            bizResponse.setRspSysId(AppParamConstant.SYS_ID);
            bizResponse.setRespCode(result.getResult().getRespCode());
            bizResponse.setRespDesc(result.getResult().getRespDesc());
            return bizResponse;
        }
        ActivityCreateResponse activityCreateResponse = result.getResult();
        /*活动ID赋值*/
        alipayMchntInfo.setActivityApplyId(activityCreateResponse.getActivityId());
        /*特殊费率申请标识赋值*/
        alipayMchntInfo.setSpecialRateApplyFlag("1");
        /*最新操作人赋值*/
        alipayMchntInfo.setLastOprId(userId);
        /* 特殊行业费率优惠默认，有且仅有一种 */
        alipayMchntInfo.setActivityType("01");
        alipayMchntInfo.setLastUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss"));
        int iReturnCode = alipayMchntInfoMapper.updateAlipayMchntInfoById(alipayMchntInfo);
        if (0 != iReturnCode) {
            rglog.error("支付宝商户信息更新失败");
            throw new BizException(RespCodeEnum.UPDATE_ALIMCHNT_INFO_ERROR.getRespCode(), RespCodeEnum.UPDATE_ALIMCHNT_INFO_ERROR.getRespDesc());
        }
        /*活动报名id*/
        alipayActivityApplyResponse.setActivityApplyId(activityCreateResponse.getActivityId());
        /*是否存在已报名的同类型活动*/
        alipayActivityApplyResponse.setHasApply(activityCreateResponse.getHasApply());

        /* 按照接口转换支付宝特殊费率申请信息并响应给请求方 */
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(alipayActivityApplyResponse);
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        AlipayActivityApplyResponse alipayActivityApplyResponse = (AlipayActivityApplyResponse) bizResponse.getResult();
        ConvertUtil.convertInput(alipayActivityApplyResponse);
    }
}